package com.scqkxx.gamebox.receiver;

import android.app.NotificationManager;
import android.content.Context;
import android.content.Intent;
import android.util.Log;

import com.avos.avoscloud.AVUser;
import com.igexin.sdk.GTIntentService;
import com.igexin.sdk.PushConsts;
import com.igexin.sdk.PushManager;
import com.igexin.sdk.message.BindAliasCmdMessage;
import com.igexin.sdk.message.FeedbackCmdMessage;
import com.igexin.sdk.message.GTCmdMessage;
import com.igexin.sdk.message.GTNotificationMessage;
import com.igexin.sdk.message.GTTransmitMessage;
import com.igexin.sdk.message.SetTagCmdMessage;
import com.igexin.sdk.message.UnBindAliasCmdMessage;
import com.scqkxx.gamebox.utils.PushGTClientUtils;
import com.scqkzqtz.base.library.utils.Base64Utils;
import com.scqkzqtz.base.library.utils.LogUtils;

import org.json.JSONObject;

/**
 * @Author: heli
 * @Description: 功能简介
 * @Time: 2018/3/27 15:52
 * @Change: 更改简介
 * @ChangeTime: 2018/3/27 15:52
 * <p>
 * * 继承 GTIntentService 接收来自个推的消息, 所有消息在线程中回调, 如果注册了该服务, 则务必要在 AndroidManifest中声明, 否则无法接受消息<br>
 * onReceiveMessageData 处理透传消息<br>
 * onReceiveClientId 接收 cid <br>
 * onReceiveOnlineState cid 离线上线通知 <br>
 * onReceiveCommandResult 各种事件处理回执 <br>
 */
public class IntentService extends GTIntentService {

    private static final String TAG = "IntentService";
    private NotificationManager mNotificationManager;

    @Override
    public void onReceiveServicePid(Context context, int pid) {
        Log.d(TAG, "onReceiveServicePid -> " + pid);
    }

    @Override
    public void onReceiveMessageData(Context context, GTTransmitMessage msg) {
        mNotificationManager = (NotificationManager) context
                .getSystemService(Context.NOTIFICATION_SERVICE);
        String appid = msg.getAppid();
        String taskid = msg.getTaskId();
        String messageid = msg.getMessageId();
        byte[] payload = msg.getPayload();
        String pkg = msg.getPkgName();
        String cid = msg.getClientId();
        // 第三方回执调用接口，actionid范围为90000-90999，可根据业务场景执行
        boolean result = PushManager.getInstance().sendFeedbackMessage(context, taskid, messageid, 90001);
        if (payload != null) {
            String data = new String(payload);
            try {
                LogUtils.e(TAG, "messages:" + data);
                JSONObject jsonobject = new JSONObject(data);//str表示你取到的内容
                String type = jsonobject.optString("type");
                String content = jsonobject.optString("content");
                String title = jsonobject.optString("title");
                String url = jsonobject.optString("url");
                String jumpObjectId = jsonobject.optString("jumpObjectId");

                switch (type) {
                    default:
                        Intent intent = new Intent(context, IntentPushActivity.class);
                        intent.putExtra("type", "GeTuiPush");
                        intent.putExtra("payload", Base64Utils.setEncryption(data) + "");
                        showNotification(context, title, content, intent);
                        break;
                }


            } catch (org.json.JSONException e) {
                e.printStackTrace();
                LogUtils.e(TAG, "推送解析出错:" + data);
            } catch (Exception e) {
                LogUtils.e(TAG, "推送解析位置错误:" + data);
            }
        }

    }

    @Override
    public void onReceiveClientId(Context context, String clientid) {
        Log.e(TAG, "onReceiveClientId -> " + "clientid = " + clientid);
        if (AVUser.getCurrentUser() != null) {
            AVUser.getCurrentUser().put("cid", clientid);
            AVUser.getCurrentUser().saveInBackground();
        }
        synchronized (clientid) {
            PushGTClientUtils.setGTClient(context, clientid);
        }
    }

    @Override
    public void onReceiveOnlineState(Context context, boolean online) {
        Log.d(TAG, "onReceiveOnlineState -> " + (online ? "online" : "offline"));
    }

    @Override
    public void onReceiveCommandResult(Context context, GTCmdMessage cmdMessage) {
        Log.d(TAG, "onReceiveCommandResult -> " + cmdMessage);

        int action = cmdMessage.getAction();

        if (action == PushConsts.SET_TAG_RESULT) {
            setTagResult((SetTagCmdMessage) cmdMessage);
        } else if (action == PushConsts.BIND_ALIAS_RESULT) {
            bindAliasResult((BindAliasCmdMessage) cmdMessage);
        } else if (action == PushConsts.UNBIND_ALIAS_RESULT) {
            unbindAliasResult((UnBindAliasCmdMessage) cmdMessage);
        } else if ((action == PushConsts.THIRDPART_FEEDBACK)) {
            feedbackResult((FeedbackCmdMessage) cmdMessage);
        }
    }

    @Override
    public void onNotificationMessageArrived(Context context, GTNotificationMessage message) {
        Log.d(TAG, "onNotificationMessageArrived -> " + "appid = " + message.getAppid() + "\ntaskid = " + message.getTaskId() + "\nmessageid = "
                + message.getMessageId() + "\npkg = " + message.getPkgName() + "\ncid = " + message.getClientId() + "\ntitle = "
                + message.getTitle() + "\ncontent = " + message.getContent());
    }

    @Override
    public void onNotificationMessageClicked(Context context, GTNotificationMessage message) {
        Log.d(TAG, "onNotificationMessageClicked -> " + "appid = " + message.getAppid() + "\ntaskid = " + message.getTaskId() + "\nmessageid = "
                + message.getMessageId() + "\npkg = " + message.getPkgName() + "\ncid = " + message.getClientId() + "\ntitle = "
                + message.getTitle() + "\ncontent = " + message.getContent());
    }

    private void setTagResult(SetTagCmdMessage setTagCmdMsg) {
        String sn = setTagCmdMsg.getSn();
        String code = setTagCmdMsg.getCode();

        Log.d(TAG, "settag result sn = " + sn + ", code = " + code);
    }

    private void bindAliasResult(BindAliasCmdMessage bindAliasCmdMessage) {
        String sn = bindAliasCmdMessage.getSn();
        String code = bindAliasCmdMessage.getCode();

        Log.d(TAG, "bindAlias result sn = " + sn + ", code = " + code);

    }

    private void unbindAliasResult(UnBindAliasCmdMessage unBindAliasCmdMessage) {
        String sn = unBindAliasCmdMessage.getSn();
        String code = unBindAliasCmdMessage.getCode();

        Log.d(TAG, "unbindAlias result sn = " + sn + ", code = " + code);

    }

    private void feedbackResult(FeedbackCmdMessage feedbackCmdMsg) {
        String appid = feedbackCmdMsg.getAppid();
        String taskid = feedbackCmdMsg.getTaskId();
        String actionid = feedbackCmdMsg.getActionId();
        String result = feedbackCmdMsg.getResult();
        long timestamp = feedbackCmdMsg.getTimeStamp();
        String cid = feedbackCmdMsg.getClientId();

        Log.d(TAG, "onReceiveCommandResult -> " + "appid = " + appid + "\ntaskid = " + taskid + "\nactionid = " + actionid + "\nresult = " + result
                + "\ncid = " + cid + "\ntimestamp = " + timestamp);
    }

    /**
     * 构建通知.
     *
     * @param context      context
     * @param title        显示标题
     * @param msg          显示内容
     * @param resultIntent 点击后需要跳转的页面
     * @param
     */

    private void showNotification(Context context, String title, String msg,
                                  Intent resultIntent) {
        NotificationUtils notificationUtils = new NotificationUtils(this);
        notificationUtils.sendNotification(context, title, msg, resultIntent);
    }
}
